import { PageContainer } from '@ant-design/pro-components';
import {
  Button,
  Cascader,
  Col,
  Flex,
  Form,
  Input,
  InputNumber,
  Modal,
  Row,
  Select,
  Table,
  Tag,
} from 'antd';
import React, { useEffect, useState } from 'react';
import styles from './index.less';
import { CaretDownOutlined, CaretUpOutlined, PlusOutlined } from '@ant-design/icons';
import useEditModal from '@/utils/useEditModal';
import { addCategoryApi, editCategoryApi, getAllCategoryListApi } from '@/services/category';

const Category: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<any[]>([]);
  const [expandedRowKeys, setExpandedRowKeys] = useState<number[]>([]);
  const getData = async () => {
    setLoading(true);
    const { rsCode, body } = await getAllCategoryListApi();
    setLoading(false);
    if (rsCode === '00000000' && Array.isArray(body)) {
      const list = body.map((v: any) => {
        return {
          ...v,
          children: v.children?.sort((a: any, b: any) => a.sort - b.sort),
        };
      });
      setData(list.sort((a, b) => a.sort - b.sort));
    }
  };
  const {
    loading: editLoading,
    form: editForm,
    currentData,
    setCurrentData,
    onOk,
    onCancel,
  } = useEditModal({
    editApi: editCategoryApi,
    addApi: addCategoryApi,
    successCb: () => getData(),
  });

  useEffect(() => {
    getData();
  }, []);

  return (
    <PageContainer>
      <Row gutter={[30, 30]} style={{ padding: '15px 30px' }}>
        <div className={styles.search_box}>
          <Form style={{ width: '100%' }}>
            <Row gutter={[20, 20]}>
              <Col span={24}>
                <Flex align="center" justify="flex-end" gap={15}>
                  <Button
                    color="primary"
                    variant="outlined"
                    icon={<CaretDownOutlined />}
                    onClick={() => {
                      setExpandedRowKeys(data.map((item) => item.id));
                    }}
                  >
                    展开所有标签
                  </Button>
                  <Button
                    color="primary"
                    variant="outlined"
                    icon={<CaretUpOutlined />}
                    onClick={() => {
                      setExpandedRowKeys([]);
                    }}
                  >
                    收起所有标签
                  </Button>
                  <Button
                    color="primary"
                    variant="outlined"
                    icon={<PlusOutlined />}
                    onClick={() => setCurrentData({})}
                  >
                    新增一级标签
                  </Button>
                </Flex>
              </Col>
            </Row>
          </Form>
        </div>
        <div className={styles.table_box}>
          <Table
            dataSource={data}
            pagination={false}
            scroll={{ x: 1200 }}
            loading={loading}
            rowKey="id"
            expandable={{
              indentSize: 30,
              expandedRowKeys,
              onExpandedRowsChange: (keys) => setExpandedRowKeys(keys as number[]),
            }}
            columns={[
              Table.EXPAND_COLUMN,
              {
                title: '编号',
                dataIndex: 'id',
                key: 'id',
                width: 200,
                render: (text) => <Tag color="#87d068">{text}</Tag>,
              },
              {
                title: '名称',
                dataIndex: 'name',
                key: 'name',
                width: 200,
              },
              {
                title: 'ID路径',
                dataIndex: 'idPath',
                key: 'idPath',
                width: 150,
                align: 'center',
              },
              {
                title: '备注',
                dataIndex: 'remark',
                key: 'remark',
              },
              {
                title: '序号',
                dataIndex: 'sort',
                key: 'remark',
                width: 100,
                align: 'center',
                render: (text) => <Tag color="blue">{text}</Tag>,
              },
              {
                title: '操作',
                key: 'action',
                width: 200,
                fixed: 'right',
                align: 'center',
                render: (_, record) => (
                  <Flex align="center" justify="center">
                    <Button
                      type="link"
                      onClick={() => {
                        let parentIds = undefined;
                        if (record.idPath.includes('-')) {
                          parentIds = record.idPath
                            .split('-')
                            .filter(Boolean)
                            .slice(0, -1)
                            .map((id: string) => Number(id));
                        }
                        setCurrentData({
                          id: record.id,
                          name: record.name,
                          parentIds,
                          remark: record.remark,
                          sort: record.sort,
                          parentId: parentIds ? parentIds.at(-1) : undefined,
                        });
                      }}
                    >
                      编辑
                    </Button>
                    <Button
                      type="link"
                      onClick={() => {
                        const list = record.idPath
                          .split('-')
                          .filter(Boolean)
                          .map((id: string) => Number(id));
                        setCurrentData({
                          parentIds: list,
                          parentId: record.id,
                        });
                      }}
                    >
                      添加子标签
                    </Button>
                  </Flex>
                ),
              },
            ]}
          />
        </div>
      </Row>
      <Modal
        title={currentData?.id ? '编辑标签' : '新增标签'}
        centered
        width={600}
        open={!!currentData}
        onCancel={onCancel}
        onOk={onOk}
        okButtonProps={{ loading: editLoading }}
      >
        <Form
          form={editForm}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 16 }}
          style={{ padding: '20px 0' }}
        >
          <Form.Item label="ID" name="id" hidden />
          <Form.Item label="ID" name="parentId" hidden />
          <Form.Item label="名称" name="name" rules={[{ required: true, message: '请输入名称' }]}>
            <Input placeholder="请输入名称" />
          </Form.Item>
          <Form.Item label="父级标签" name="parentId">
            <Select
              placeholder="父级标签"
              options={data}
              fieldNames={{ label: 'name', value: 'id' }}
              disabled={!currentData?.parentId}
            />
          </Form.Item>
          <Form.Item label="备注" name="remark">
            <Input placeholder="请输入备注" />
          </Form.Item>
          <Form.Item
            label="序号"
            name="sort"
            rules={[{ required: true, message: '请输入序号' }]}
            initialValue={1}
          >
            <InputNumber placeholder="请输入序号" min={1} style={{ width: 120 }} controls />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default Category;
